import sceneConf from '../../confs/scene-conf'
import camera from './camera'
import light from './light'
import background from '../objects/background'

class Scene {
  constructor() {}
  init() {
    this.instance = new THREE.Scene()
    const renderer = this.renderer = new THREE.WebGLRenderer({
      // 抗锯齿
      antialias: true,
      canvas: canvas,
      // 保存绘制的缓冲区
      preserveDrawingBuffer: true,
    })

    // scene 开启阴影
    renderer.shadowMap.enabled = true
    renderer.shadowMap.type = THREE.PCFShadowMap

    // 设置场景背景颜色
    // renderer.setClearColor(sceneConf.backgroundColor)
    this.camera = camera
    this.camera.init()

    this.light = light
    this.light.init()
    // camera 实例加入到 scene实例
    this.instance.add(this.camera.instance)
    // 测试相机观察视角
    this.axesHelper = new THREE.AxesHelper(100)
    this.instance.add(this.axesHelper)


    for (let lightType in this.light.instances) {
      this.instance.add(this.light.instances[lightType])
    }

    // background 初始化
    this.background = background
    this.background.init()
    this.background.instance.position.z = -84
    this.camera.instance.add(this.background.instance)
  }

  reset() {
    this.camera.reset()
    this.light.reset()
  }

  // 渲染 camera下的scene 渲染的场景
  render() {
    this.renderer.render(this.instance, this.camera.instance)
  }

  /**
   * 场景更新camera 位置
   */
  updateCameraPosition(targetPosition) {
    this.camera.updatePosition(targetPosition)
    this.light.updatePosition(targetPosition)
  }

  /**
   * 添加分数
   */
  addScore(scoreInstance) {
    this.currentScore = scoreInstance
    this.camera.instance.add(scoreInstance)
    scoreInstance.position.x = -20
    scoreInstance.position.y = 40
  }

  /**
   * 更新分数 dispatched
   */
  updateScore(scoreInstance) {
    this.camera.instance.remove(this.currentScore)
    this.currentScore = scoreInstance
    this.camera.instance.add(scoreInstance)
    scoreInstance.position.x = -20
    scoreInstance.position.y = 40
  }
}

export default new Scene()